<?php 
    require_once ("/mnt/sdcard/www/Includes/simplecms-config.php");
    require_once  ("/mnt/sdcard/www/Includes/connectDB.php");
    include("/mnt/sdcard/www/Includes/header.php");

    createLog("phoneList");

    define(LEND_POSSIBLE, 0);
    define(LEND_IMPOSSIBLE, 1);
    define(LEND_DEVTEAM, 2);
    define(LEND_ING_APPROVAL, 3);
    define(LEND_REPAIR ,9);

    define(OWNER_QATEAM ,0);
    define(OWNER_LEND_DEVICE_SHORT ,1);
    define(OWNER_LEND_DEVICE_LONG ,2);
    define(OWNER_DEVTEAM ,3);

    define(CABLE_NONE, 0);
    define(CABLE_USB, 1);
    define(CABLE_CHARGER, 2);
    define(CABLE_USB_CHARGER, 3);

    if (!logged_on())
    {
        echo "
            <div class='alert alert-danger'>
                <strong>접근 오류!</strong> 로그인 후에 이용할 수 있는 서비스 입니다.
            </div>
        ";
    }

    $query = "SELECT * FROM deviceInfo WHERE deleted = '0' ORDER BY deviceState ASC, deviceOS ASC";
    $statement = $databaseConnection->prepare($query);
    $statement->execute();
    $statement->store_result();
    $total_record = $statement->affected_rows;

    $statement->bind_result($id, $deviceOS, $deviceName, $deviceModel, $deviceVersion, $deviceResolution, $team, $name, $startDate, $endDate, $returnDate, $carrier, $deviceNumber, $etc, $deviceID, $deviceState, $deviceOwner, $deleted);
?>

<div class="navbar navbar-inverse navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            </button>
            <?php
                if (logged_on())
                {
                    $url = "/phoneList.php";
                }
                else
                {
                    $url = "/index.php";
                }
            ?>
            <a class="navbar-brand" href="<?php echo $url ?>">Device Management System</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="/index.php">Home</a></li>
                <?php
                    if (logged_on())
                    {
                        echo '
                            <li class="active"><a href="/phoneList.php">기기목록</a></li>
                            <li><a href="/approval.php">결재</a></li>
                        ';
                    }
                ?>
                <?php
                    if (is_admin())
                    {
                        echo '
                            <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">관리메뉴<b class="caret"></b></a>
                                <ul class="dropdown-menu">
                                    <li><a href="/phoneEnroll.php">기기등록</a></li>
                                    <li><a href="/manage.php">기기관리</a></li>
                                    <!--<li class="divider"></li>
                                    <li class="dropdown-header">Nav header</li>
                                    <li><a href="#">Separated link</a></li>
                                    <li><a href="#">One more separated link</a></li>-->
                                </ul>
                            </li>
                        ';
                    }
                ?>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <?php
                    if (logged_on())
                    {
                        if (is_admin())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(관리자)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                        elseif (is_member())
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(정회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";   
                        }
                        else
                        {
                            echo "
                                <li><a href='#'>환영합니다, {$_SESSION['username']}(준회원)</a></li>
                                <li><a href='/logoff.php'>로그아웃</a></li>
                            ";
                        }
                    }
                    else
                    {
                        echo "
                            <form action='index.php' method='post' class='navbar-form navbar-right'>
                                <div class='form-group'>
                                    <input type='text' name='username' placeholder='아이디' class='form-control'>
                                </div>
                                <div class='form-group'>
                                    <input type='password' name='password' placeholder='비밀번호' class='form-control'>
                                </div>
                                <button type='submit' name='submit' class='btn btn-success'>로그인</button>
                                <a class='btn btn-warning' href='register.php'>회원가입</a></p>
                            </form>
                        ";
                    }
                ?>
            </ul>
        </div><!--/.navbar-collapse -->
    </div>
</div>

<div class="container">
    <?php if(!logged_on()) :?>    
    <p>로그인이 필요한 서비스입니다.</p>
    <?php elseif($total_record == 0) :?>        
    <p>등록된 기기가 없습니다.</p>
    <?php else :?>
    <p><form id="form1" action="phoneLend.php" method="post"><button type="submit" name="device_lend" class="btn btn-primary">대여하기</button>
    <?php
        if(is_admin())
        {
            echo("&nbsp;<button type=submit name=device_del class='btn btn-danger'>삭제하기</button>");
        }
    ?>
    &nbsp;&nbsp;등록기기: <?php echo $total_record ?>대</p>
    <div class="table-responsive">
    <div class="panel panel-primary">
        <div class="panel-heading">기기목록</div>
            <table class="table table-hover table-striped">
                <thead><tr>
                    <!-- <th><input type="checkbox" name="list[]" onclick="checkAllorNot(this)"></th> -->
                    <th class="text-center">#</th>
                    <th>운영체제</th>
                    <th>모델명</th>
                    <th>해상도</th>
                    <th>버전</th>
                    <th>기기명</th>
                    <th class="text-center">기기상태</th>
                    <th>통신사</th>
                    <?php
                        if(is_admin())
                        {
                            echo("
                                <th>번호</th>
                                <th class='text-center'>팀</th>
                                <th class='text-center'>이름</th>
                                <th class='text-center'>대여시작일</th>
                                <th class='text-center'>대여종료일</th>
                                <th class='text-center'>기기소유</th>
                                <th class='text-center'>기기반납일</th>
                                <th>비고</th>
                            ");
                        }
                        elseif(is_member())
                        {
                            echo("
                                <th>번호</th>
                                <th class='text-center'>팀</th>
                                <th class='text-center'>이름</th>
                                <th class='text-center'>대여시작일</th>
                                <th class='text-center'>대여종료일</th>
                                <th class='text-center'>기기소유</th>
                                <th class='text-center'>기기반납일</th>
                                <th>비고</th>
                            ");
                        }
                        ?>
                </tr></thead>

            <?php 
                while($statement->fetch()) :
            ?>

                <?php
                    switch($deviceState)
                    {
                        case LEND_POSSIBLE:
                            $tag = "";
                            $chebox = "";
                            break;
                        case LEND_ING_APPROVAL:
                            $tag = "";
                            $chebox = "";
                            break;
                        case LEND_IMPOSSIBLE:
                        case LEND_DEVTEAM:
                            $tag = "";
                            $chebox = "disabled";
                            break;
                        case LEND_REPAIR:
                            $tag = "";
                            $chebox = "disabled";
                            break;
                    }
                ?>
                <tr <?php echo $tag ?>>
                    <td class='text-center'><input type="checkbox" name="list[]" value="<?php echo $id ?>" <?php echo $chebox?>></td>
                    <td><?php echo $deviceOS ?></td>
                    <td><?php echo $deviceModel ?></td>
                    <td><?php echo $deviceResolution ?></td>
                    <td><?php echo $deviceVersion ?></td>
                    <td><?php echo $deviceName ?></td>
                    <?php
                        switch($deviceState)
                        {
                            case LEND_POSSIBLE:
                                echo("<td class='text-center'><span class='label label-success'>대여가능</span></td>");
                                break;
                            case LEND_IMPOSSIBLE:
                                echo("<td class='text-center'><span class='label label-danger'>대여중</span></td>");
                                break;
                            case LEND_DEVTEAM:
                                echo("<td class='text-center'><span class='label label-danger'>개발팀대여중</span></td>");
                                break;
                            case LEND_ING_APPROVAL:
                                $query_approval = "SELECT device_id FROM approval WHERE device_id='$id' and approval_state='0'";
                                $statement_approval = $databaseConnection->prepare($query_approval);
                                $statement_approval->execute();
                                $statement_approval->store_result();

                                echo("<td class='text-center'><span class='label label-info'>결재진행중 ($statement_approval->affected_rows)</span></td>");
                                $statement_approval->close();
                                break;
                            case LEND_REPAIR:
                                echo("<td class='text-center'><span class='label label-warning'>수리중</span></td>");
                                break;                                
                        }
                    ?>
                    <td><?php echo $carrier ?></td>
                    <?php

                        if($startDate == "0000-00-00")
                        {
                            $startDate = "";
                        }

                        if($endDate == "0000-00-00")
                        {
                            $endDate = "";
                        }

                        if($returnDate == "0000-00-00")
                        {
                            $returnDate = "";
                        }

                        // 날짜 계산
                        $dateTag_returnDate = "class=\"text-center\"";

                        if($returnDate != "")
                        {
                            $today = date("Y-m-d", mktime(0,0,0,date('m'),date('d'),date('Y')));
                            $end = strtotime($today);
                            $start_returnDate = strtotime($returnDate);
                            $day = 86400;

                            $remain_returnDate = ($start_returnDate - $end) / $day;

                            if($remain_returnDate <= 7 && $remain_returnDate > 0)
                            {
                                $dateTag_returnDate = "class=\"text-center warning\"";
                            }
                            elseif($remain_returnDate <= 0)
                            {
                                $dateTag_returnDate = "class=\"text-center danger\"";
                            }
                            else
                            {
                                $dateTag_returnDate = "class=\"text-center\"";
                            }
                        }

                        // 날짜 계산
                        $dateTag_endDate = "class=\"text-center\"";

                        if($startDate != "" && $endDate != "")
                        {
                            $today = date("Y-m-d", mktime(0,0,0,date('m'),date('d'),date('Y')));
                            $end = strtotime($today);
                            $start_endDate = strtotime($endDate);
                            $day = 86400;

                            $remain_endDate = ($start_endDate - $end) / $day;

                            if($remain_endDate == 0)    // 오늘이 반납일 일때
                            {
                                $dateTag_endDate = "class=\"text-center warning\"";
                            }
                            elseif($remain_endDate < 0) // 반납일이 지났을 경우
                            {
                                $dateTag_endDate = "class=\"text-center danger\"";
                            }
                            else
                            {
                                $dateTag_endDate = "class=\"text-center\"";
                            }
                        }
                            
                        if(is_admin())
                        {
                            echo("
                                <td>$deviceNumber</td>
                                <td class='text-center'>$team</td>
                                <td class='text-center'>$name</td>
                                <td class='text-center'>$startDate</td>
                                <td $dateTag_endDate>$endDate</td>
                            ");

                            switch($deviceOwner)
                            {
                                case OWNER_QATEAM:
                                    echo("<td class='text-center'>QA팀</td>");
                                    break;
                                case OWNER_LEND_DEVICE_SHORT:
                                    echo("<td class='text-center'>대여기기</td>");
                                    break;
                                case OWNER_LEND_DEVICE_LONG:
                                    echo("<td class='text-center'>장기대여기기</td>");
                                    break;
                                case OWNER_DEVTEAM:
                                    echo("<td class='text-center'>개발팀</td>");
                                    break;                                
                            }

                            echo("<td $dateTag_returnDate>$returnDate</td>");
                            echo("<td>$etc</td>");
                        }
                        if(is_member())
                        {
                            echo("
                                <td>$deviceNumber</td>
                                <td class='text-center'>$team</td>
                                <td class='text-center'>$name</td>
                                <td class='text-center'>$startDate</td>
                                <td $dateTag_endDate>$endDate</td>
                            ");

                            switch($deviceOwner)
                            {
                                case OWNER_QATEAM:
                                    echo("<td class='text-center'>QA팀</td>");
                                    break;
                                case OWNER_LEND_DEVICE_SHORT:
                                    echo("<td class='text-center'>대여기기</td>");
                                    break;
                                case OWNER_LEND_DEVICE_LONG:
                                    echo("<td class='text-center'>장기대여기기</td>");
                                    break;
                                case OWNER_DEVTEAM:
                                    echo("<td class='text-center'>개발팀</td>");
                                    break;                                
                            }

                            echo("<td $dateTag_returnDate>$returnDate</td>");
                            echo("<td>$etc</td>");
                        }
                    ?>
                </tr>
                
            <?php endwhile?>
            </table>
    </div>
    </div>
    </form>
    <?php endif?>
    <?php $statement->close();?>
</div>

<!-- 기기 대여목록 시작 -->
<div class="container">
    <?php
        if(isset($_SESSION['userid']))
        {
            $query = "SELECT id, user_id, deviceOS, deviceName, deviceModel, deviceVersion, deviceResolution, deviceState, carrier, deviceNumber, team, name, startDate, endDate, deviceOwner, etc, cable FROM deviceInfo JOIN users_lend on deviceInfo.id = users_lend.device_id WHERE user_id = ? AND deleted = '0' AND returned = '0' ORDER BY startDate DESC";
            $statement = $databaseConnection->prepare($query);
            $statement->bind_param('i', $_SESSION['userid']);
            $statement->execute();
            $statement->store_result();
            $total_record = $statement->affected_rows;
        }
    ?>

    <?php if(!logged_on()) :?>
        로그인이 필요한 서비스입니다.
    <?php elseif($total_record == 0) :?>
    <?php else :?>

        <?php $statement->bind_result($id, $userid, $deviceOS, $deviceName, $deviceModel, $deviceVersion, $deviceResolution, $deviceState, $carrier, $deviceNumber, $team, $name, $startDate, $endDate, $deviceOwner, $etc, $cable); ?>
        <p><form id="form2" method="post"><button type="submit" name="device_return" onclick="submitForm('phoneReturn.php')" class="btn btn-success">반납하기</button>
        &nbsp;<button type="submit" name="device_continue" onclick="submitForm('phoneContinue.php')" class="btn btn-warning">연장하기</button>
        &nbsp;&nbsp;대여기기: <?php echo $total_record ?>대</p>
        <div class="table-responsive">
        <div class="panel panel-primary">
            <div class="panel-heading">대여기기 목록</div>
                <table class="table table-hover table-striped">
                    <thead><tr>
                        <!-- <th><input type="checkbox" name="list[]" onclick="checkAllorNot(this)"></th> -->
                        <th class="text-center">#</th>
                        <th>운영체제</th>
                        <th>모델명</th>
                        <th>해상도</th>
                        <th>버전</th>
                        <th>기기명</th>
                        <th class="text-center">기기상태</th>
                        <th>통신사</th>
                        <th>번호</th>
                        <th class="text-center">팀</th>
                        <th class="text-center">이름</th>
                        <th class="text-center">대여시작일</th>
                        <th class="text-center">대여종료일</th>
                        <th class="text-center">주변기기</th>
                        <th class="text-center">기기소유</th>
                        <th>비고</th>
                    </tr></thead>

                <?php 
                    while($statement->fetch()) :

                        // 날짜 계산
                        $today = date("Y-m-d", mktime(0,0,0,date('m'),date('d'),date('Y')));
                        $end = strtotime($today);
                        $start_endDate = strtotime($endDate);
                        $day = 86400;

                        $remain_endDate = ($start_endDate - $end) / $day;

                        if($remain_endDate <= 2 && $remain_endDate >= 0)    // 반납일 2일 전 또는 반납일이 오늘 일 경우
                        {
                            $dateTag_endDate = "class=\"text-center warning\"";
                        }
                        elseif($remain_endDate < 0)     // 반납일이 지났을 경우
                        {
                            $dateTag_endDate = "class=\"text-center danger\"";
                        }
                        else
                        {
                            $dateTag_endDate = "class=\"text-center\"";
                        }
                ?>
                    <tr>
                        <td class='text-center'><input type="checkbox" name="list[]" value="<?php echo $id ?>"></td>
                        <td><?php echo $deviceOS ?></td>
                        <td><?php echo $deviceModel ?></td>
                        <td><?php echo $deviceResolution ?></td>
                        <td><?php echo $deviceVersion ?></td>
                        <td><?php echo $deviceName ?></td>
                        <?php
                            switch($deviceState)
                            {
                                case LEND_POSSIBLE:
                                    echo("<td class='text-center'><span class='label label-success'>대여가능</span></td>");
                                    break;
                                case LEND_IMPOSSIBLE:
                                    echo("<td class='text-center'><span class='label label-danger'>대여중</span></td>");
                                    break;
                                case LEND_DEVTEAM:
                                    echo("<td class='text-center'><span class='label label-danger'>개발팀대여중</span></td>");
                                    break;
                                case LEND_REPAIR:
                                    echo("<td class='text-center'><span class='label label-warning'>수리중</span></td>");
                                    break;                                
                            }
                        ?>
                        <td><?php echo $carrier ?></td>
                        <td><?php echo $deviceNumber ?></td>
                        <td class='text-center'><?php echo $team ?></td>
                        <td class='text-center'><?php echo $name ?></td>
                        <td class='text-center'><?php echo $startDate ?></td>
                        <td <?php echo $dateTag_endDate ?>><?php echo $endDate ?></td>
                        <?php
                            switch($cable)
                            {
                                case CABLE_NONE:
                                    echo("<td class='text-center'>대여안함</td>");
                                    break;
                                case CABLE_USB:
                                    echo("<td class='text-center'>USB케이블</td>");
                                    break;
                                case CABLE_CHARGER:
                                    echo("<td class='text-center'>충전기</td>");
                                    break;
                                case CABLE_USB_CHARGER:
                                    echo("<td class='text-center'>USB케이블+충전기</td>");
                                    break;
                            }
                        ?>
                        <?php
                            switch($deviceOwner)
                            {
                                case OWNER_QATEAM:
                                    echo("<td class='text-center'>QA팀</td>");
                                    break;
                                case OWNER_LEND_DEVICE_SHORT:
                                    echo("<td class='text-center'>대여기기</td>");
                                    break;
                                case OWNER_LEND_DEVICE_LONG:
                                    echo("<td class='text-center'>장기대여기기</td>");
                                    break;
                                case OWNER_DEVTEAM:
                                    echo("<td class='text-center'>개발팀</td>");
                                    break;                                
                            }

                            echo("<td>$etc</td>");
                        ?>
                    </tr>
                
                <?php endwhile?>
                <?php $statement->close();?>
                </table>
        </div>
        </div>
        </form>
                           
    <?php endif?>
</div>

<?php
    include ("/mnt/sdcard/www/Includes/footer.php");
 ?>